%MY_RPY2R Roll-pitch-yaw angles to SO(3) rotation matrix
%
% R = MY_RPY2R(ROLL, PITCH, YAW, OPTIONS) is an SO(3) orthonornal rotation
% matrix (3x3) equivalent to the specified roll, pitch, yaw angles angles.
% These correspond to rotations about the Z, Y, X axes respectively. If
% ROLL, PITCH, YAW are column vectors (Nx1) then they are assumed to
% represent a trajectory and R is a three-dimensional matrix (3x3xN), where
% the last index corresponds to rows of ROLL, PITCH, YAW.
%
% R = MY_RPY2R(RPY, OPTIONS) as above but the roll, pitch, yaw angles are
% taken from the vector (1x3) RPY=[ROLL,PITCH,YAW]. If RPY is a matrix
% (Nx3) then R is a three-dimensional matrix (3x3xN), where the last index
% corresponds to rows of RPY which are assumed to be [ROLL,PITCH,YAW].
%
% Options::
%  'deg'      Compute angles in degrees (radians default)
%  'xyz'      Rotations about X, Y, Z axes (for a robot gripper)
%  'zyx'      Rotations about Z, Y, X axes (for a mobile robot, default)
%  'yxz'      Rotations about Y, X, Z axes (for a camera)
%  'arm'      Rotations about X, Y, Z axes (for a robot arm)
%  'vehicle'  Rotations about Z, Y, X axes (for a mobile robot)
%  'camera'   Rotations about Y, X, Z axes (for a camera)
%
% Note::
% - Toolbox rel 8-9 has XYZ angle sequence as default.
% - ZYX order is appropriate for vehicles with direction of travel in the X
%   direction.  XYZ order is appropriate if direction of travel is in the Z
%   direction.
% - 'arm', 'vehicle', 'camera' are synonyms for 'xyz', 'zyx' and 'yxz'
%   respectively.
%
% See also TR2RPY, EUL2TR.
% 

function R = my_rpy2tr(roll,varargin)
    opt.order = {'zyx', 'xyz', 'yxz', 'arm', 'vehicle', 'camera'};
    opt.deg = false;
    [opt,args] = tb_optparse(opt, varargin);
    if numcols(roll) == 3
        yaw = roll(:,3);
        pitch = roll(:,2);
        roll = roll(:,1);
    elseif nargin >= 3
        pitch = args{1};
        yaw = args{2};
    else
        error('SMTB:rpy2r:badarg', 'bad arguments')
    end

    % optionally convert from degrees
    if opt.deg
        d2r = pi/180.0;
        roll = roll * d2r;
        pitch = pitch * d2r;
        yaw = yaw * d2r;
    end

    % ZYX order
    if numrows(roll) == 1
        R = my_rotz(yaw) * my_roty(pitch) * my_rotx(roll);
    else
        R = zeros(3,3,numrows(roll));
        for i=1:numrows(roll)
            R(:,:,i) = my_rotz(yaw(i)) * my_roty(pitch(i)) * my_rotx(roll(i));
        end
    end

end